<?php
/**
 * Created by PhpStorm.
 * User: wufubin
 * Date: 2017/1/3
 * Time: 13:17
 */

namespace Home\Controller;


use Common\Controller\HomeController;
use Common\Model\GoodsAttrModel;
use Common\Model\GoodsListModel;
use Common\Model\GoodsModel;
use Org\Util\Cart;

class ContentController extends HomeController {
    public function index() {
        $headConf = [
            'title' => '商品详情',
            'js' => ['list']
        ];
        $this->assign('headConf', $headConf);
        $gid = i('get.gid');
        //获取商品数据
        $goodsData = (new GoodsModel())->alias('g')->join("shop_goods_detail d on g.gid=d.gid")->where("g.gid=$gid")->find();
        $goodsData['small_pic'] = explode(',', $goodsData['small_pic']);
        $goodsData['medium_pic'] = explode(',', $goodsData['medium_pic']);
        $goodsData['big_pic'] = explode(',', $goodsData['big_pic']);
        //获取规格数据并重组
        $specData = (new GoodsAttrModel())->alias('ga')->join("shop_type_attr ta on ga.taid=ta.taid")->where("ta.tatype=1 and ga.gid=$gid")->select();
        $temp = [];
        foreach ($specData as $k => $v) {
            $temp[$v['taname']][] = $v;
        }
        $this->assign('goodsData', $goodsData);
        $this->assign('specData', $temp);
        $this->display();
    }

    public function ajaxGetTotal() {
        $gid = $_POST['gid'];
        $combine = rtrim($_POST['combine'], ',');
        $total = (new GoodsListModel())->where("gid=$gid and combine='{$combine}'")->getField('total');
        echo $total;
    }

    public function ajaxAddToCart() {
        $gid = $_POST['gid'];
        $num = $_POST['num'];
        $options = $_POST['options'];
        //根据gid获取商品数据
        $oneGoodsData = (new GoodsModel())->where("gid = $gid")->field('gname,shopprice')->find();
        $data = [
            'id' => $gid, // 商品 ID
            'name' => $oneGoodsData['gname'],// 商品名称
            'num' => $num, // 商品数量
            'price' => $oneGoodsData['shopprice'], // 商品价格
            'options' => $options// 其他参数如价格、颜色、可以为数组或字符串
        ];
        (new Cart())->add($data);
        echo 1;
    }
}